package com.gz.mylife.app;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.AdvertFragment;
import com.gz.mylife.adapter.AdvertFragmentAdapter;
import com.gz.mylife.adapter.BaseAdapterHelper;
import com.gz.mylife.adapter.QuickAdapter;
import com.gz.mylife.widget.FooterView;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.PageIndicator;
import com.gz.mylife.widget.FooterView.OnFooterViewRefreshListener;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.BrandedProductsListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.po.AdvertInfo;
import com.zl.smartmall.library.po.BrandedProductsInfo;
import com.zl.smartmall.library.util.CrashHandler;


/**
 * 
 * @author 陈希然
 *
 */
public class FragmentMallBrandedProducts extends Fragment implements OnClickListener, OnFooterViewRefreshListener, OnItemClickListener, OnLoadingCoverRefreshListener, OnRefreshListener<ListView>, OnPageChangeListener {

	private static final String TAG = FragmentMallBrandedProducts.class.getSimpleName();
	private int mBrandId;
	private int mPage;
	private AdvertFragmentAdapter mAdvertFragmentAdapter;
	private Context mContext;
	private DisplayImageOptions mIconOption;
	private QuickAdapter<BrandedProductsInfo> mAdapter;
	
	private FooterView mFooterView;
	private LoadingCover mLoadingCover;
	private PageIndicator mPageIndicator;
	private PullToRefreshListView mListView;
	private View mConvertView;
	private View mHeadView;
	private ViewPager mViewPager;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		CrashHandler.d(TAG, TAG + " onCreate");
		
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		case R.id.action_my_order:
//			Intent intent = new Intent(getActivity(), MyOrdersActivity.class);
//			startActivity(intent);
//			return true;
//
//		default:
			return super.onOptionsItemSelected(item);
//		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, TAG + " onCreateView");
		if(mConvertView == null){
			CrashHandler.d(TAG, "convertView is null, init the whole elements");
			mConvertView = inflater.inflate(R.layout.fragment_mall_branded_products, container, false);
			init(inflater);
		}
		
		return mConvertView;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		CrashHandler.d(TAG, TAG + " onDestory");
		
//		mHandler.release();
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		CrashHandler.d(TAG, TAG + " onDestroyView");
		((ViewGroup) mConvertView.getParent()).removeView(mConvertView);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		CrashHandler.d(TAG, TAG + " onPause");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		CrashHandler.d(TAG, TAG + " onResume");
//		mAdapter.notifyDataSetChanged();
//		if(cartGoodsCount!=null){
//			int num = PreferenceModel.getInt(Define.KEY_SHOPPING_CART_NUM, 0);
//			String numStr = num>9?9+"+":num+"";
//			cartGoodsCount.setText(numStr);
//		}
	}	
	
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.layout_search:
			Intent intentSearch = new Intent(getActivity(), ShoppingSearchActivity.class);
			startActivity(intentSearch);
			break;
		}
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	}

	@Override
	public void onFooterViewRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.SCROLL));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if(view == mFooterView || view == mHeadView) {
			return;
		}
		Intent intent = new Intent(mContext, ProductDetail.class);
		intent.putExtra("productId", mAdapter.getItem((int) id).getProductId());
		intent.putExtra("shopId", mAdapter.getItem((int) id).getShopId());
		intent.putExtra("mBrandId", mBrandId);
		startActivity(intent);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, "下拉加载品牌商品列表");
		loadDataFromServer(buildListener(RequestCode.PULL));
	};

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		
	}
	
	private QuickAdapter<BrandedProductsInfo> buildAdater(){
		return new QuickAdapter<BrandedProductsInfo>(mContext, R.layout.fragment_mall_branded_products_product_item, new ArrayList<BrandedProductsInfo>()) {

			@Override
			protected void convert(BaseAdapterHelper helper, BrandedProductsInfo item) {
//				TextView originalCost = helper.getView(R.id.tv_original_cost);
//				originalCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
//				LinearLayout layoutLabel = helper.getView(R.id.layout_labels);
//				for(int i = 0; i < layoutLabel.getChildCount(); i++) {
//					layoutLabel.getChildAt(i).setVisibility(View.INVISIBLE);
//				}
//				for(int i = 0; i < item.getLabels().length && i < layoutLabel.getChildCount(); i++) {
//					((TextView) layoutLabel.getChildAt(i)).setText(item.getLabels()[i]);
//					layoutLabel.getChildAt(i).setVisibility(View.VISIBLE);
//					if("包邮".equals(item.getLabels()[i])) {
//						layoutLabel.getChildAt(i).setBackgroundResource(R.drawable.bg_free_express);
//					}else {
//						layoutLabel.getChildAt(i).setBackgroundResource(R.drawable.bg_gift);
//					}
//					layoutLabel.getChildAt(i).setPadding(Tools.dip2px(mContext, 3), 0, Tools.dip2px(mContext, 3), 0);
//				}
//				double discount = item.getCurrentCost() / item.getOriginalCost();
//				String discountStr = item.getCurrentCost() == item.getOriginalCost() ? "无折扣" :
//					new DecimalFormat("0.0").format(discount * 10) + "折";
//				if(item.getCurrentCost() == item.getOriginalCost()) {
//					helper.setVisible(R.id.tv_discount, View.GONE);
//				}else {
//					helper.setVisible(R.id.tv_discount, View.VISIBLE);
//				}
				helper.setImageUrl(R.id.iv_product, item.getProductIcon(), mIconOption)
					  .setText(R.id.tv_product_intro, item.getProductIntro())
//					  .setText(R.id.tv_original_cost, "原价 " + new DecimalFormat("0.00").format(item.getOriginalCost()))
					  .setText(R.id.tv_current_cost, "￥" + new DecimalFormat("0.00").format(item.getCurrentCost()))
					  .setText(R.id.shop_time, "已售  " + item.getSaleNum())
					  .setText(R.id.tv_shop_name, item.getShopName());
//					  .setText(R.id.tv_sale_num, item.getSaleNum() > 0 ? item.getSaleNum() + "人认为值" : "")
//					  .setText(R.id.tv_discount, discountStr);
			}
		};
	}
	
	private DisplayImageOptions buildIconOptions(){
		return new DisplayImageOptions.Builder()
		.resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .showImageOnLoading(R.drawable.ic_load_image_square_default)
        .showImageOnFail(R.drawable.ic_load_image_square_fail)
        .showImageForEmptyUri(R.drawable.ic_load_image_square_fail)
        .imageScaleType(ImageScaleType.EXACTLY)
        .build();
	}
	
	private BrandedProductsListener buildListener(RequestCode requestCode) {
		return new BrandedProductsListener(mContext, requestCode) {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NOTHING);
				mFooterView.onRefreshComplete();
				mListView.setOnScrollListener(null);
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
				if(mAdvertFragmentAdapter.getCount() > 1) {
					mViewPager.setVisibility(View.VISIBLE);
//					mPageIndicator.setVisibility(View.VISIBLE);
				}else {
					mViewPager.setVisibility(View.GONE);
//					mPageIndicator.setVisibility(View.GONE);
				}
				
				if(requestCode == RequestCode.PULL) {
					mAdapter.clear();
				}
			}
			
			@Override
			public void onResponseSuccess(List<AdvertInfo> advertInfos,
					List<BrandedProductsInfo> brandedProductsInfos) {
				// TODO Auto-generated method stub
				if(advertInfos.size() > 0) {
					refreshAdvert(advertInfos);
					mViewPager.setVisibility(View.VISIBLE);
//					mPageIndicator.setVisibility(View.VISIBLE);
				}else {
					mViewPager.setVisibility(View.GONE);
//					mPageIndicator.setVisibility(View.GONE);
				}
				if(this.requestCode == RequestCode.PULL) {
					mAdapter.clear();
				}
				mAdapter.addAll(brandedProductsInfos);

				if (brandedProductsInfos.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
					mFooterView.onRefreshComplete();
					mListView.setOnScrollListener(null);
					
				} else {
					mFooterView.onRefreshSuccess();
					mListView.setOnScrollListener(mFooterView);
				}
				
				mLoadingCover.onRefreshSuccess();
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
				
				//如果本地加载就联网
				if(this.requestCode == RequestCode.CACHE) {
//					mPullList.setRefreshing();
					loadDataFromServer(buildListener(RequestCode.PULL));
				}
				
				CrashHandler.d(TAG, "品牌商品列表requestCode = " + this.requestCode);
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
				mFooterView.onRefreshFailed();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
		};
	}
	
	private void init(LayoutInflater inflater){
		mAdvertFragmentAdapter = new AdvertFragmentAdapter(getChildFragmentManager());
		mBrandId = getActivity().getIntent().getIntExtra("brandId", mBrandId);
		mContext = getActivity().getApplicationContext();
		mAdapter = buildAdater();
		mIconOption = buildIconOptions();
		
		mFooterView = (FooterView) inflater.inflate(R.layout.footer_view, null);
		mFooterView.setOnFooterViewRefreshListener(this);
		
		mLoadingCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		
		mHeadView = inflater.inflate(R.layout.fragment_mall_branded_products_head, null);
		mHeadView.findViewById(R.id.layout_search).setOnClickListener(this);
		mViewPager = (ViewPager) mHeadView.findViewById(R.id.pager);
		mViewPager.setAdapter(mAdvertFragmentAdapter);
		mPageIndicator = (PageIndicator) mHeadView.findViewById(R.id.page_indicator);
		mPageIndicator.setViewPage(mViewPager);
		mPageIndicator.setOnPageChangeListener(this);
//		mPicture = (ImageView) mHeadView.findViewById(R.id.iv_picture);
		mListView = (PullToRefreshListView) mConvertView.findViewById(R.id.list);
		mListView.getRefreshableView().addFooterView(mFooterView);
		mListView.getRefreshableView().addHeaderView(mHeadView);
		mListView.setAdapter(mAdapter);
		mListView.setOnRefreshListener(this);
		mListView.setOnItemClickListener(this);
		mListView.setOnScrollListener(mFooterView);
		
		loadDataFromServer(buildListener(RequestCode.PULL));
//		ISmartMall.getInstance().getBrandedProducts(true, mBrandId, mPage, buildListener(RequestCode.CACHE));
//		ISmartMall.getInstance().getBrandedProducts(false, mBrandId, mPage, buildListener(RequestCode.PULL));
	}
	
	private void loadDataFromServer(BrandedProductsListener brandedProductsListener) {		
		if(brandedProductsListener.getRequestCode() == RequestCode.PULL) {
			mPage = 1;
		}else if(brandedProductsListener.getRequestCode() == RequestCode.SCROLL) {
			mPage++;
		}
		ISmartMall.getInstance().getBrandedProducts(false, mBrandId, mPage, brandedProductsListener);
	}
	
	private void refreshAdvert(List<AdvertInfo> advertInfos){
		CrashHandler.d(TAG, "advert size = " + advertInfos.size());
		List<AdvertFragment> fragments = new ArrayList<AdvertFragment>();
		for(int i = 0; i < advertInfos.size(); i++){
			AdvertFragment fragment = AdvertFragment.newInstance(null, 
					advertInfos.get(i).getPicture());
			fragments.add(fragment);
		}
		if(advertInfos.size() > 1) {
			mPageIndicator.setVisibility(View.VISIBLE);
		}else {
			mPageIndicator.setVisibility(View.GONE);
		}
		
		mAdvertFragmentAdapter.clear();
		mAdvertFragmentAdapter.addAll(fragments);
		mAdvertFragmentAdapter.notifyDataSetChanged();
		mPageIndicator.notifyDataSetChanged();
	}
	
}
